package com.xydtech.web.controller.system;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.constant.AppConstants;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.enums.UserStatus;
import com.xydtech.common.exception.user.UserBlockedException;
import com.xydtech.common.exception.user.UserDeleteException;
import com.xydtech.common.utils.ServletUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.framework.jwt.utils.JwtUtils;
import com.xydtech.framework.shiro.service.SysPasswordService;
import com.xydtech.system.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private RedisTemplate redisTemplate;

    /** token超时时间 */
    private static Long TOKEN_TIME_OUT = 30 * 60L;
    /** refresh_token超时时间 */
    private static Long REFRESH_TOKEN_TIME_OUT = 3 * 24 * 60 * 60L;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        mmap.put("systemName", XydtechBusiPlatConfig.getName());
        mmap.put("systemLogo", XydtechBusiPlatConfig.getLogo());
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * APP端登录接口
     * @param username
     * @param password
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author Daniel
     * @date 2021/12/12 9:25
     */
    @PostMapping("/appApi/login")
    @ResponseBody
    public AjaxResult jwtLogin(String username, String password, String clientId) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            //账号和密码不能为空
            return AjaxResult.error(AjaxResult.Type.SYS_USER_PASS_NOT_EMPTY);
        }

        SysUser user = userService.selectUserByLoginName(username);
        if (user == null) {
            //用户不存在/密码错误!
            return AjaxResult.error(AjaxResult.Type.SYS_USER_NAME_PASS_INVALID);
        }

        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            //对不起，您的账号已被删除!
            return AjaxResult.error(AjaxResult.Type.SYS_USER_ACCOUNT_DEL);
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            return AjaxResult.error(AjaxResult.Type.SYS_USER_ACCOUNT_DISABLED);
        }

        if (!passwordService.matches(user, password)) {
            return AjaxResult.error(AjaxResult.Type.SYS_USER_NAME_PASS_INVALID);
        }

        String userId = user.getUserId() + "";

        //绑定用户和手机之间的关系，用作消息推送
        //TODO 推送注释
        //UniPushBindAlias bindAlias = new UniPushBindAlias(userId, clientId);
        //ApiResult<Void> bindResult = uniPushService.bindAlias(bindAlias);

        //生成token并将将其值塞入到缓存中，缓存时间为30分钟
        String token = JwtUtils.createToken(userId, user.getPassword(), TOKEN_TIME_OUT * 1000);
        redisTemplate.opsForValue().set(AppConstants.REDIS_SAVE_TOKEN_KEY + userId, token, TOKEN_TIME_OUT, TimeUnit.SECONDS);

        //生成refresh_token并塞入到缓存中，缓存时间为3天
        String refreshToken = JwtUtils.createToken(userId, user.getPassword(), REFRESH_TOKEN_TIME_OUT * 1000);
        redisTemplate.opsForValue().set(AppConstants.REDIS_SAVE_REFRESH_TOKEN_KEY + userId, refreshToken, REFRESH_TOKEN_TIME_OUT, TimeUnit.SECONDS);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("refresh_token", refreshToken);

        return AjaxResult.success("登录成功,请妥善保管您的token信息", data);
    }

    /**
     * APP端刷新Token
     * @param refreshToken
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author Daniel
     * @date 2021-12-21 10:20:03
     */
    @PostMapping("/appApi/refreshToken")
    @ResponseBody
    public AjaxResult refreshToken(@RequestParam(required = true) String refreshToken) {
        String salt = getSalt();//盐值
        if (StringUtils.isEmpty(refreshToken)) {
            return AjaxResult.error(AjaxResult.Type.SYS_REFRESH_TOKEN_INVALID);
        }

        /**
         * 思路：
         * 1. 首先通过REFRESH_TOKEN获取userId，判断是否为有效的refresh_token
         * 2. 然后根据userId去redis数据库中查询是否存在refresh_token，如果存在，继续，如果不存在，抛异常
         * 3. 如果存在的时候，根据用户名密码校验refresh_token的有效性
         */
        String userId = JwtUtils.getUserId(refreshToken);
        if (userId == null) {
            throw new AccountException("refresh_token 验证失败");
        }
        SysUser user = userService.selectUserById(Long.parseLong(userId), salt);
        if (user == null) {
            throw new AuthenticationException("用户数据不存在");
        }

        try {
            //首先校验Redis中是否存储该值，且是否相等，如存在且相等，那么继续
            String redisDbToken = (String) redisTemplate.opsForValue().get(AppConstants.REDIS_SAVE_REFRESH_TOKEN_KEY + userId);
            if (refreshToken.equals(redisDbToken)) {
                JwtUtils.verify(userId, user.getPassword(), refreshToken);

                if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                    throw new UserDeleteException();
                }

                if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                    throw new UserBlockedException();
                }
            } else {
                throw new TokenExpiredException("refresh_token已过期");
            }
        } catch (Exception e) {
            logger.info("对用户[" + userId + "]进行refresh_token的jwt登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }

        //生成新的token和refresh_token扔给前端
        String token = JwtUtils.createToken(userId, user.getPassword(), TOKEN_TIME_OUT * 1000);
        redisTemplate.opsForValue().set(AppConstants.REDIS_SAVE_TOKEN_KEY + userId, token, TOKEN_TIME_OUT, TimeUnit.SECONDS);

        //生成refresh_token并塞入到缓存中，缓存时间为3天
        refreshToken = JwtUtils.createToken(userId, user.getPassword(), REFRESH_TOKEN_TIME_OUT * 1000);
        redisTemplate.opsForValue().set(AppConstants.REDIS_SAVE_REFRESH_TOKEN_KEY + userId, refreshToken, REFRESH_TOKEN_TIME_OUT, TimeUnit.SECONDS);


        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("refresh_token", refreshToken);

        return AjaxResult.success("刷新成功,请妥善保管您的token信息", data);
    }

    /**
     * APP退出登录
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author Daniel
     * @date 2022-3-16 16:48:18
     */
    @PostMapping("/appApi/logout")
    @ResponseBody
    public AjaxResult logout(String clientId) {
        //获取到token
        String token = ServletUtils.getRequest().getHeader("token");
        String userId = JwtUtils.getUserId(token);

        if (!Objects.isNull(token)) {
            /**
             * 思路：
             * 1. 解绑用户UNIPUSH消息推送的设备绑定关系
             * 2. 删除Redis中的token信息
             */
            //TODO 推送注释
            //if (!Objects.isNull(clientId)) {
            //    UniPushBindAlias bindAlias = new UniPushBindAlias(userId, clientId);
            //
            //    uniPushService.unBindAlias(bindAlias);
            //}

            //删除token和refreshToken
            redisTemplate.delete(AppConstants.REDIS_SAVE_TOKEN_KEY + userId);
            redisTemplate.delete(AppConstants.REDIS_SAVE_REFRESH_TOKEN_KEY + userId);
            return AjaxResult.success();
        } else {
            //无效的token信息
            return AjaxResult.error(AjaxResult.Type.SYS_TOKEN_INVALID);
        }
    }


    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }
}
